package com.hrbxlh.action;


import java.io.File;
import java.io.IOException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.hrbxlh.pojo.TaskLibrary;
import com.hrbxlh.util.*;
import com.hrbxlh.vo.ExpreLibraryVO;
import com.hrbxlh.vo.TaskLibraryVO;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hrbxlh.actionImpl.ChapterActionImpl;
import com.hrbxlh.actionImpl.CourseActionImpl;

/**
 * -------------------------------------------------------
 * Copyright (c) 2017, 鑫联华信息科技股份有限公司
 * All rights reserved.
 * FileName：ChapterAction.java
 * Description：章节action类     注：章节即资源的意思，如果遇见写了资源的字样，其实就是章节
 * History：
 * Date           Author               Desc
 * 2017.9.19		xzx					   建立
 * -------------------------------------------------------
 */
@Controller
public class ChapterAction<T> {


	@Autowired
	@Qualifier("chapterActionImpl")
	private ChapterActionImpl chapterActionImpl;

	@Autowired
	@Qualifier("courseActionImpl")
	private CourseActionImpl courseActionImpl;

	/**
	 * @description  资源管理列表（分页） 展示所有章节信息 （老师）
	 * @param jsonStr  pageNow  pageSize  chapterName搜索条件
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getChapterList", method = RequestMethod.POST)
	public void getChapterList(String jsonStr, HttpServletRequest request, HttpServletResponse response) {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		try {
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			if(ParamConvertUtil.getSpecialWordMark(preParamMap)){
				resultMap.put("result", "fail");
				resultMap.put("failMsg", "参数含有特殊字符");
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
				return;
			}
			//获取章节列表信息
			Map<String, Object> resultAllMap = chapterActionImpl.getChapterList(preParamMap, request);
			if(resultAllMap != null){
				//返回值
				resultMap.put("chapterList", resultAllMap.get("chapterList"));
				resultMap.put("totalPage", resultAllMap.get("totalPage"));
				resultMap.put("pageNow", resultAllMap.get("pageNow"));
			}
			resultMap.put("pageSize", preParamMap.get("pageSize"));
			resultMap.put("chapterName", preParamMap.get("chapterName"));
			resultMap.put("addTestMark", preParamMap.get("addTestMark"));
			resultMap.put("result","success");
			logger.info("获取资源列表操作,参数为："+jsonStr);
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (Exception e) {
			resultMap.put("result","fail");
			resultMap.put("failMsg","查询资源列表失败");
			e.printStackTrace();
			logger.error("获取资源列表页面出现异常getChapterList", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}

	/**
	 * @description  添加章节上半部分
	 * @param chapterName addTestMark
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addChapterTopOne", method = RequestMethod.POST)
	public void addChapterTopOne(String jsonStr, HttpServletRequest request, HttpServletResponse response) {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		try {
			//获取页面参数值
			Map<String, Object> preParamMap = mapper.readValue(jsonStr, returnMap.getClass());
			if(ParamConvertUtil.getSpecialWordMark(preParamMap)){
				resultMap.put("result", "fail");
				resultMap.put("failMsg", "参数含有特殊字符");
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
				return;
			}
			resultMap = chapterActionImpl.addChapterTopOne(preParamMap,request);
			logger.info("添加章节上半部分,参数为："+jsonStr);
			courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
		} catch (Exception e) {
			resultMap.put("result","fail");
			resultMap.put("failMsg","添加章节上半部分失败");
			e.printStackTrace();
			logger.error("添加章节上半部分出现异常addChapterTopOne", e);
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e1) {
				e1.printStackTrace();
			}
		}
	}



	/***
	 * @description 添加章节下半部分之---课件
	 * @param   // 课件文件
	 * @param request
	 * @param courseware
	 * 将上传的实验文档，作业 ，备课材料，答案.（doc）转换成html
	 * 课件转换为pdf
	 *
	 * 20180427商莹改---作业改成上传excel格式、实验手册、备课材料改成在线编辑、课程答案去掉
	 * 实验手册、备课材料改成前台给后台传html的字符串。
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addChapterCourseWare", method = RequestMethod.POST)
	public void  addChapterCourseWare  (HttpServletRequest request,
								 @RequestParam(value = "courseware") CommonsMultipartFile courseware,
								 @RequestParam(value = "chapterId") int chapterId,
								 HttpServletResponse response
	){
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		FileUpload fileUpload = new FileUpload();
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> returntMap = new HashMap<String,Object>();
		try {
			Map<String, Object> checkMark = FileUpload.checkFileSize(new CommonsMultipartFile[]{courseware}, new double[]{50});
			if(!(Boolean) checkMark.get("result")){
				reJsonStr = "{\"result\":\"error\",\"failMsg\":\""+checkMark.get("failMsg").toString()+"\"}";
				courseActionImpl.responseStream(response, reJsonStr);
				return;
			}
			Map<String, Object> postfixMap = fileUpload.getFilePostfixReasonableMark(new CommonsMultipartFile[] {courseware}, new String[][]{{"pptx"}}, new String[] {"课件"});
			if(postfixMap.get("result").toString().equals("fail")){
				courseActionImpl.responseStream(response, mapper.writeValueAsString(postfixMap));
				return;
			}
			logger.info("开始添加章节信息");
			//通过章节id查询章节信息
			Map<String,Object> paramMap = new HashMap<>();
			paramMap.put("coursemark",1);
			paramMap.put("chapterId",chapterId);
			Map<String,Object> chapterMap =  chapterActionImpl.getOneChapter(paramMap);
			//课程标识
			String courseMark = String.valueOf(chapterMap.get("courseMark"));
			//上传课件，视频，作业(20170622将以下方法改为map类型,并且将作业对应的word文档也修改)
			Map<String, Object> uploadMapOne = fileUpload.fileUploadParam(courseware, request, 1, 3,courseMark);
			String coursewareName = (String) uploadMapOne.get("result");
			logger.info("获取上传课件名称："+courseware.getOriginalFilename());
			String coursewareNameHtml = (String) uploadMapOne.get("resultHtml");
			logger.info("获取上传课件pdf名称："+coursewareNameHtml);
			//课件
			resultMap.put("coursewareName", coursewareName);
			resultMap.put("coursewareNameHtml", coursewareNameHtml);
			resultMap.put("chapterId", chapterId);
			//添加课件
			Map<String, Object> addResult = chapterActionImpl.addChapterCourseWare(resultMap, request);
			String result = Boolean.parseBoolean(String.valueOf(addResult.get("flag")))==true?"success":"fail";
			/*String filename = courseware.getOriginalFilename().substring(0,courseware.getOriginalFilename().lastIndexOf("."));
			filename = filename+courseMark+".pptx";*/
			returntMap.put("result",result);
			returntMap.put("filename",coursewareName);
			returntMap.put("courseMark",courseMark);
			returntMap.put("coursewareNameHtml", coursewareNameHtml);
			courseActionImpl.responseStream(response, mapper.writeValueAsString(returntMap));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("添加章节下半部分之---课件出现异常addChapterCourseWare", e);
			reJsonStr = "{\"result\":\"error\"}";
			courseActionImpl.responseStream(response, reJsonStr);
		}
	}


	/***
	 * @description 添加章节---课程材料
	 * @param   // 课程材料
	 * @param request
	 * @param packageFile
	 * @param chapterId
	 * 将上传的实验文档，作业 ，备课材料，答案.（doc）转换成html
	 * 课件转换为pdf
	 *
	 * 20180427商莹改---作业改成上传excel格式、实验手册、备课材料改成在线编辑、课程答案去掉
	 * 实验手册、备课材料改成前台给后台传html的字符串。
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addChapterPackageFile", method = RequestMethod.POST)
	public void  addChapterPackageFile  (HttpServletRequest request,
								 int chapterId,
								 @RequestParam(value = "packageFile") CommonsMultipartFile packageFile,
								 HttpServletResponse response
	){

		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		FileUpload fileUpload = new FileUpload();
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> returntMap = new HashMap<String,Object>();
		try {
			Map<String, Object> checkMark = FileUpload.checkFileSize(new CommonsMultipartFile[]{ packageFile}, new double[]{50});
			if(!(Boolean) checkMark.get("result")){
				reJsonStr = "{\"result\":\"error\",\"failMsg\":\""+checkMark.get("failMsg").toString()+"\"}";
				courseActionImpl.responseStream(response, reJsonStr);
				return;
			}

			Map<String, Object> postfixMap = fileUpload.getFilePostfixReasonableMark(new CommonsMultipartFile[] {packageFile}, new String[][]{{"zip","rar"}}, new String[] {"课程材料"});
			if(postfixMap.get("result").toString().equals("fail")){
				courseActionImpl.responseStream(response, mapper.writeValueAsString(postfixMap));
				return;
			}
			//通过章节id查询章节信息
			Map<String,Object> paramMap = new HashMap<>();
			paramMap.put("coursemark",1);
			paramMap.put("chapterId",chapterId);
			Map<String,Object> chapterMap =  chapterActionImpl.getOneChapter(paramMap);
			//课程标识
			String courseMark = String.valueOf(chapterMap.get("courseMark"));
			Map<String, Object> uploadMapSix = fileUpload.fileUploadParam(packageFile, request, 1, 0,courseMark);
			String packageFileName = String.valueOf(uploadMapSix.get("result")) ;

			//课程材料文件包
			resultMap.put("packageFile", packageFileName);
			resultMap.put("chapterId", chapterId);
			//添加课件
			Map<String, Object> addResult = chapterActionImpl.addChapterPackageFile(resultMap);
			String result = Boolean.parseBoolean(String.valueOf(addResult.get("flag")))==true?"success":"fail";
			returntMap.put("result",result);
			returntMap.put("filename", packageFileName);
			returntMap.put("courseMark",courseMark);
			courseActionImpl.responseStream(response, mapper.writeValueAsString(returntMap));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("添加章节---课程材料出现异常addChapterPackageFile", e);
			reJsonStr = "{\"result\":\"error\"}";
			courseActionImpl.responseStream(response, reJsonStr);
		}
	}


	/***
	 * @description 添加章节---课后作业
	 * @param   // 作业文件
	 * @param request
	 * @param homeworkexcel
	 * @param chapterId
	 * 将上传的实验文档，作业 ，备课材料，答案.（doc）转换成html
	 * 课件转换为pdf
	 *
	 * 20180427商莹改---作业改成上传excel格式、实验手册、备课材料改成在线编辑、课程答案去掉
	 * 实验手册、备课材料改成前台给后台传html的字符串。
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addChapterHomework", method = RequestMethod.POST)
	public void  addChapterHomework  (HttpServletRequest request,
								 int chapterId,
								 int mark,
								 @RequestParam(value = "homeworkexcel") CommonsMultipartFile homeworkexcel,
								 HttpServletResponse response
	){

		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		FileUpload fileUpload = new FileUpload();
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> returntMap = new HashMap<String,Object>();
		try {
			String fileName = homeworkexcel.getOriginalFilename();
			Map<String, Object> checkMark = FileUpload.checkFileSize(new CommonsMultipartFile[]{homeworkexcel}, new double[]{50});
			if(!(Boolean) checkMark.get("result")){
				reJsonStr = "{\"result\":\"error\",\"failMsg\":\""+checkMark.get("failMsg").toString()+"\"}";
				courseActionImpl.responseStream(response, reJsonStr);
				return;
			}

			Map<String, Object> postfixMap = fileUpload.getFilePostfixReasonableMark(new CommonsMultipartFile[] {homeworkexcel}, new String[][]{{"xls","xlsx"}}, new String[] {"作业"});
			if(postfixMap.get("result").toString().equals("fail")){
				courseActionImpl.responseStream(response, mapper.writeValueAsString(postfixMap));
				return;
			}
			List<TaskLibraryVO> taskList = null;
			resultMap.put("chapterId",chapterId);
			//添加章节
			Map<String, Object> addResult = chapterActionImpl.addChapterHomework(resultMap,homeworkexcel,mark);
			if ((Boolean) addResult.get("result")) {
				//通过章节id查询作业数据
				Map<String,Object> taskMap  = chapterActionImpl.getTaskLibrary(chapterId);
				returntMap.put("result", "success");
				returntMap.put("actualSumSource",addResult.get("actualSumSource"));
				returntMap.put("taskOptionList",taskMap.get("taskOptionList"));
				returntMap.put("taskManyOptionList",taskMap.get("taskManyOptionList"));
				returntMap.put("taskBlankList",taskMap.get("taskBlankList"));
				returntMap.put("taskJudgeList",taskMap.get("taskJudgeList"));
				returntMap.put("taskAnswerList",taskMap.get("taskAnswerList"));
				returntMap.put("charpterId",chapterId);
				returntMap.put("filename",fileName);
			} else {
				returntMap.put("result", "fail");
				returntMap.put("actualSumSource",0);
				returntMap.put("taskOptionList",null);
				returntMap.put("taskManyOptionList",null);
				returntMap.put("taskBlankList",null);
				returntMap.put("taskJudgeList",null);
				returntMap.put("taskAnswerList",null);
				returntMap.put("filename",fileName);
				returntMap.put("failMsg", addResult.get("errMsg"));
				returntMap.put("charpterId", chapterId);
			}
			courseActionImpl.responseStream(response, mapper.writeValueAsString(returntMap));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("添加章节---课后作业出现异常addChapterHomework", e);
			reJsonStr = "{\"result\":\"error\"}";
			courseActionImpl.responseStream(response, reJsonStr);
		}
	}


	/***
	 * @description 添加章节---实验报告
	 * @param   // 实验报告文件
	 * @param request
	 * @param expreexcel
	 * @param chapterId
	 * 将上传的实验文档，作业 ，备课材料，答案.（doc）转换成html
	 * 课件转换为pdf
	 *
	 * 20180427商莹改---作业改成上传excel格式、实验手册、备课材料改成在线编辑、课程答案去掉
	 * 实验手册、备课材料改成前台给后台传html的字符串。
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addChapterExpreexcel", method = RequestMethod.POST)
	public void  addChapterExpreexcel  (HttpServletRequest request,
									  int chapterId,
										int mark,
									  @RequestParam(value = "expreexcel") CommonsMultipartFile expreexcel,
									  HttpServletResponse response
	){

		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		FileUpload fileUpload = new FileUpload();
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> returntMap = new HashMap<String,Object>();
		try {
			Map<String, Object> checkMark = FileUpload.checkFileSize(new CommonsMultipartFile[]{expreexcel}, new double[]{50});
			if(!(Boolean) checkMark.get("result")){
				reJsonStr = "{\"result\":\"error\",\"failMsg\":\""+checkMark.get("failMsg").toString()+"\"}";
				courseActionImpl.responseStream(response, reJsonStr);
				return;
			}

			Map<String, Object> postfixMap = fileUpload.getFilePostfixReasonableMark(new CommonsMultipartFile[] {expreexcel}, new String[][]{{"xls","xlsx"}}, new String[] {"实验报告"});
			if(postfixMap.get("result").toString().equals("fail")){
				courseActionImpl.responseStream(response, mapper.writeValueAsString(postfixMap));
				return;
			}

			List<ExpreLibraryVO> expreList = null;
			resultMap.put("chapterId",chapterId);
			//添加章节
			Map<String, Object> addResult = chapterActionImpl.addChapterExpreexcel(resultMap,expreexcel,mark);
			if ((Boolean) addResult.get("result")) {
				//通过章节id查询实验报告
				expreList = chapterActionImpl.getExpreLibrary(chapterId);
				returntMap.put("result", "success");
				returntMap.put("actualSumSource",addResult.get("actualSumSource"));
				returntMap.put("expreList", expreList);
				returntMap.put("charpterId",chapterId);
			} else {
				returntMap.put("result", "fail");
				returntMap.put("actualSumSource",0);
				returntMap.put("expreList", null);
				returntMap.put("failMsg", addResult.get("errMsg"));
				returntMap.put("charpterId", chapterId);
			}
			courseActionImpl.responseStream(response, mapper.writeValueAsString(returntMap));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("添加章节---实验报告出现异常addChapterExpreexcel", e);
			reJsonStr = "{\"result\":\"error\"}";
			courseActionImpl.responseStream(response, reJsonStr);
		}
	}


	/***
	 * @description 添加章节---视频
	 * @param   // 视频文件
	 * @param request
	 * @param packageFile
	 * @param chapterId
	 * 将上传的实验文档，作业 ，备课材料，答案.（doc）转换成html
	 * 课件转换为pdf
	 *
	 * 20180427商莹改---作业改成上传excel格式、实验手册、备课材料改成在线编辑、课程答案去掉
	 * 实验手册、备课材料改成前台给后台传html的字符串。
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addChapterVideo", method = RequestMethod.POST)
	public void  addChapterVideo  (HttpServletRequest request,
										 int chapterId,
										 @RequestParam(value = "video") CommonsMultipartFile video,
										 HttpServletResponse response
	){


		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		FileUpload fileUpload = new FileUpload();
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> returntMap = new HashMap<String,Object>();
		try {
			Map<String, Object> postfixMap = fileUpload.getFilePostfixReasonableMark(new CommonsMultipartFile[] {video}, new String[][]{{"mp4"}}, new String[] {"视频"});
			if(postfixMap.get("result").toString().equals("fail")){
				courseActionImpl.responseStream(response, mapper.writeValueAsString(postfixMap));
				return;
			}
			//通过章节id查询章节信息
			Map<String,Object> paramMap = new HashMap<>();
			paramMap.put("coursemark",1);
			paramMap.put("chapterId",chapterId);
			Map<String,Object> chapterMap =  chapterActionImpl.getOneChapter(paramMap);
			//课程标识
			String courseMark = String.valueOf(chapterMap.get("courseMark"));
			//视频
			Map<String, Object> uploadMapTwo = fileUpload.fileUploadParam(video, request, 1, 0,courseMark);
			String videoName = (String) uploadMapTwo.get("result");
			//视频
			String fileName = chapterActionImpl.getFileName(video, chapterId, "videoName", videoName);
			resultMap.put("videoName", fileName);
			resultMap.put("chapterId", chapterId);
			//添加视频
			Map<String, Object> addResult = chapterActionImpl.addChapterVideo(resultMap);
			String result = Boolean.parseBoolean(String.valueOf(addResult.get("flag")))==true?"success":"fail";
			returntMap.put("result",result);
			returntMap.put("filename", fileName);
			returntMap.put("courseMark",courseMark);
			courseActionImpl.responseStream(response, mapper.writeValueAsString(returntMap));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("添加章节---视频出现异常addChapterVideo", e);
			reJsonStr = "{\"result\":\"error\"}";
			courseActionImpl.responseStream(response, reJsonStr);
		}
	}

	/***
	 * @description 添加章节--备课材料or实验手册
	 * @param   //courseMaterialNameHtml、testNameHtml
	 * @param request
	 * 将上传的实验文档，作业 ，备课材料，答案.（doc）转换成html
	 * 课件转换为pdf
	 *
	 * 20180427商莹改---作业改成上传excel格式、实验手册、备课材料改成在线编辑、课程答案去掉
	 * 实验手册、备课材料改成前台给后台传html的字符串。
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/addChapterMaterialOrTest", method = RequestMethod.POST)
	public void  addChapterMaterialOrTest  (HttpServletRequest request, String jsonStr, HttpServletResponse response){

		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> returntMap = new HashMap<String,Object>();
		try {
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//备课材料
			paramMap.put("courseMaterialName", "");
			//实验手册
			paramMap.put("testDocName", "");
			//添加章节--实验手册or备课材料
			Map<String, Object> addResult = chapterActionImpl.addChapterMaterialOrTest(paramMap,request);
			String result = Boolean.parseBoolean(String.valueOf(addResult.get("flag")))==true?"success":"fail";
			returntMap.put("result",result);
			returntMap.put("filename",addResult.get("filename"));
			courseActionImpl.responseStream(response, mapper.writeValueAsString(returntMap));
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("添加章节--备课材料or实验手册出现异常addChapterMaterialOrTest", e);
			reJsonStr = "{\"result\":\"error\"}";
			courseActionImpl.responseStream(response, reJsonStr);
		}
	}


	/**@description  跳转修改章节页面
	 * @param request  chapterId
	 * @return
	 */
	@RequestMapping(value = "/skipSaveChapter", method = RequestMethod.POST)
	public void skipSaveChapter(String jsonStr , HttpServletResponse response) {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		try {
			//获取参数
			Map<String, Object> paramMap = mapper.readValue(jsonStr, returnMap.getClass());
			//通过章节id获取全部信息
			//查询该章节的信息
			Map<String,Object> chapterMap = chapterActionImpl.getOneChapter(paramMap);
			resultMap.put("chapterMsg", chapterMap);
			resultMap.put("result", "success");
			logger.info("跳转修改章节页面,参数为:"+jsonStr);
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("跳转修改章节页面出现异常skipSaveChapter", e);
		} finally {
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}


	/***
	 * @description 修改章节---上半部分
	 * @param request  章节id 章节名称  课件文件   视频文件  作业文件  类型（实验、课程）  作业对应的word文档  备课材料  课程答案
	 * @param chapterId
	 * @param addTestMark
	 * @param chapterName
	 * 将上传的试验文档，作业，备课材料，答案转换成html
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/saveChapterTop", method = RequestMethod.POST)
	public void  saveChapterTop  (HttpServletRequest request,String jsonStr, HttpServletResponse response) {
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//返回字符串
		String reJsonStr = "";
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> returntMap = new HashMap<>();
		try {
			Map<String, Object> paramMap = mapper.readValue(jsonStr, returntMap.getClass());

			if (courseActionImpl.paramCheck(String.valueOf(paramMap.get("chapterName")), response, resultMap, mapper)) return;
				//修改章节
				Map<String, Object> resultMarkMap = chapterActionImpl.saveChapterTop(paramMap, request);
				//成功，跳转到列表页面
				if ((Boolean) resultMarkMap.get("result")) {
					returntMap.put("result", "success");
					returntMap.put("charpterId", paramMap.get("chapterId"));
					returntMap.put("failMsg", "");
					//失败，跳转到错误页面
				} else {
					returntMap.put("result", "fail");
					returntMap.put("failMsg", resultMarkMap.get("errMsg").toString());
					returntMap.put("charpterId", paramMap.get("chapterId"));
				}
			courseActionImpl.responseStream(response, mapper.writeValueAsString(returntMap));
		} catch (Exception e) {
			e.printStackTrace();
			reJsonStr= "{\"result\":\"error\"}";
			logger.error("修改章节---上半部分出现异常saveChapterTop", e);
			courseActionImpl.responseStream(response, reJsonStr);
		}
	}


	/***
	 * @description 删除章节的某个文件
	 * @param request  章节id   文件
	 * @param chapterId
	 * @param fileName
	 * 将上传的试验文档，作业，备课材料，答案转换成html
	 */
	@SuppressWarnings("finally")
	@RequestMapping(value = "/delChapterFile", method = RequestMethod.POST)
	public void  delChapterFile  (HttpServletRequest request,String jsonStr, HttpServletResponse response) {
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//返回字符串
		String reJsonStr = "";
		ObjectMapper mapper = new ObjectMapper();
		Map<String,Object> returntMap = new HashMap<>();
		try {
			Map<String, Object> paramMap = mapper.readValue(jsonStr, returntMap.getClass());
			//修改章节
			returntMap = chapterActionImpl.delChapterFile(paramMap);
			courseActionImpl.responseStream(response, mapper.writeValueAsString(returntMap));
		} catch (Exception e) {
			e.printStackTrace();
			reJsonStr= "{\"result\":\"error\"}";
			logger.error("修改章节---上半部分出现异常saveChapterTop", e);
			courseActionImpl.responseStream(response, reJsonStr);
		}
	}


	/**
	 * @description  查询某一个章节的详细信息
	 * @param jsonStr request  chapterId
	 * @param response
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getOneChapter", method = RequestMethod.POST)
	public void getOneChapter(String jsonStr, HttpServletResponse response)  {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		try {
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			//查询该章节的信息
			Map<String,Object> chapterMap = chapterActionImpl.getOneChapter(paramMap);
			resultMap.put("chapterMsg", chapterMap);
			//文件前缀路径
			String[] keysArray = {"server_address", "project_name","tomcatUrl"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String url = (String)urlmap.get("tomcatUrl")+(String)urlmap.get("project_name")+"upload/course/";
			resultMap.put("url", url);
			logger.info("查询章节信息,参数为："+jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("查询章节信息出现异常getOneChapter", e);
		} finally {
			//返回页面
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @description  批量删除章节信息
	 * @param jsonStr  chapterIds  jsonStr =["1","2","3"...]
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/delChapters", method = RequestMethod.POST)
	public void delChapters(String jsonStr, HttpServletResponse response)  {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//成功失败标识
		String resultMark = "fail";
		//用于转换参数
		List<String> list = new ArrayList<String>();
		try {
			//获取参数值
			List<String> paramList = mapper.readValue(jsonStr, list.getClass());
			//删除操作
			Map<String, String> delResult = chapterActionImpl.delChapters(paramList);
			//返回成功失败
			resultMark = (delResult.get("result").equals("true")) ? "success" : "fail";
			resultMap.put("result", resultMark);
			if(resultMark.equals("fail")){
				resultMap.put("failMsg", delResult.get("errorMsg"));
			}
			logger.info("删除资源，参数为："+jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("删除资源出现异常delChapters", e);
		} finally {
			//返回页面
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @description  作业or实验报告将html代码存入数据库。并将html代码变成网页，转换成word文件，上传到服务器
	 * @param jsonStr  {chapterId，homewokHtmlStr,expreHtmlStr}
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addHtmlChapter", method = RequestMethod.POST)
	public void addHtmlChapter(String jsonStr, HttpServletResponse response)  {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//成功失败标识
		String resultMark = "fail";
		//用于转换参数
		Map<String,Object> paramMap = new HashMap<>();
		try {
			//获取参数值
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			//将html代码插入数据库等一系列操作
			Map<String, String> delResult = chapterActionImpl.addHtmlChapter(paramMap);
			//返回成功失败
			resultMark = (delResult.get("result").equals("true")) ? "success" : "fail";
			resultMap.put("modalName",delResult.get("homeworkModelName"));
			resultMap.put("result", resultMark);
			resultMap.put("failMsg", delResult.get("errorMsg"));
			resultMap.put("filename",delResult.get("filename"));
			logger.info("将作业or实验报告html代码插入数据库，参数为："+jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("将作业or实验报告html代码插入数据库出现异常delChapters", e);
		} finally {
			//返回页面
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @description  维护课程--章节详情/修改（可以在线编辑备课材料、实验手册、作业、实验报告）
	 * @param jsonStr  {chapterId，courseMaterialName,testDocName、taskHtml、expreHtml}
	 * @param response
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/OnlineEditingChapter", method = RequestMethod.POST)
	public void OnlineEditingChapter(String jsonStr, HttpServletResponse response)  {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		//成功失败标识
		String resultMark = "fail";
		//用于转换参数
		Map<String,Object> paramMap = new HashMap<>();
		try {
			//获取参数值
			paramMap = mapper.readValue(jsonStr, paramMap.getClass());
			//将html代码插入数据库等一系列操作
			Map<String, String> delResult = chapterActionImpl.OnlineEditingChapter(paramMap);
			//返回成功失败
			resultMark = (delResult.get("result").equals("true")) ? "success" : "fail";
			resultMap.put("result", resultMark);
			if(resultMark.equals("fail")){
				resultMap.put("failMsg", delResult.get("errorMsg"));
			}
			logger.info("在线编辑备课材料、实验手册、作业、实验报告，参数为："+jsonStr);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("在线编辑备课材料、实验手册、作业、实验报告出现异常delChapters", e);
		} finally {
			//返回页面
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}

	/**@description  修改作业or实验报告时先走这个action判断是否有学习记录
	 * @param request  chapterId、courseId
	 * @return
	 */
	@RequestMapping(value = "/getHistoryStudyByChapIdAndCourseId", method = RequestMethod.POST)
	public void getHistoryStudyByChapIdAndCourseId(String jsonStr , HttpServletResponse response) {

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//存放返回值
		Map<String, Object> returnMap = new HashMap<String, Object>();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();
		//日志信息
		Logger logger = Logger.getLogger(ChapterAction.class.getName());
		try {
			//获取参数
			Map<String, Object> paramMap = mapper.readValue(jsonStr, returnMap.getClass());
			//通过章节id、courseId获取是否有作业or实验报告的记录
			resultMap = chapterActionImpl.getHistoryStudyByChapIdAndCourseId(paramMap);
			logger.info("跳转修改章节页面,参数为:"+jsonStr);
		} catch (Exception e) {
			resultMap.put("result", "fail");
			e.printStackTrace();
			logger.error("修改作业or实验报告判断是否有学习记录出现异常skipSaveChapter", e);
		} finally {
			try {
				courseActionImpl.responseStream(response, mapper.writeValueAsString(resultMap));
			} catch (JsonProcessingException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * markdown上传图片的接口
	 * @param file
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/editormdPic", method = RequestMethod.POST)
	public void editormdPic (@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request, HttpServletResponse response) throws Exception{

		Map<String,Object> returntMap = new HashMap<>();

		//转换json格式工具
		ObjectMapper mapper = new ObjectMapper();
		//保存
		try {
			String trueFileName = file.getOriginalFilename();

			String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));

			String fileName = System.currentTimeMillis()+suffix;

			String[] keysArray = {"tomcatUrl", "project_name","server_address"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			String path = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/course/media/"+fileName;
//			String path = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/course/images/"+fileName;
			File saveFile = new File(path);
			if (!saveFile.exists()) {
				String s = path.substring(0,path.lastIndexOf("/") + 1);
				File saveFileDir = new File(s);
				saveFileDir.mkdirs();
			}
			/*File targetFile = new File(path, fileName);
			if(!targetFile.exists()){
				targetFile.mkdirs();
			}*/
//			String url = String.valueOf(urlmap.get("server_address"))+String.valueOf(urlmap.get("project_name"))+"upload/course/media"+fileName;
			String url ="media/"+fileName;
			file.transferTo(saveFile);
			returntMap.put("url", url);
			returntMap.put("success", 1);
			returntMap.put("message", "upload success!");
			courseActionImpl.responseStream(response, mapper.writeValueAsString(returntMap));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	/**
	 * 商莹
	 * @param 上传的图片的base64编码字符串
	 * @param 图片名称 imageName
	 * @return  上传or修改实验报告的图片
	 * @throws IOException
	 */
	@RequestMapping(value = "/addOrUpdateTestImage", method = RequestMethod.POST)
	public void addOrUpdateTestImage(String jsonStr, HttpServletResponse response)
			throws Exception {
		//日志信息
		Logger logger = Logger.getLogger(SiteAction.class.getName());
		ObjectMapper mapper = new ObjectMapper();
		//存放结果值
		Map<String,Object> resultMap = new HashMap<String,Object>();

		try {
			//获取参数值
			Map<String,Object> paramMap = mapper.readValue(jsonStr, resultMap.getClass());
			String imageName = String.valueOf(paramMap.get("imageName"));
			String imageStr = String.valueOf(paramMap.get("imageStr"));
			String[] keysArray = {"tomcatUrl", "project_name","server_address"};
			Map<String, Object> urlmap = ConfigFileUtil.getFileMessage("UtilFile.properties", keysArray);
			/*// 获取上传文件类型的扩展名,先得到.的位置，再截取从.的下一个位置到文件的最后，最后得到扩展名
			String ext = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
			// 对扩展名进行小写转换
			ext = ext.toLowerCase();
			if(!ext.equals("")&&ext!=null){
				if(!ext.equals("png")&&!ext.equals("jpg")&&!ext.equals("jpeg")){
					resultMap.put("result","fail");
					resultMap.put("failMsg","图片格式不正确");
					return;
				}
			}*/
			//判断文件夹存不存在,不存在就创建
			String path = String.valueOf(urlmap.get("tomcatUrl"))+String.valueOf(urlmap.get("project_name"))+"upload/images"+"/"+imageName;
//			String path = "C:\\Users\\Administrator\\Desktop\\xxbg\\test\\"+imageName;
			File saveFile = new File(path);
			if (!saveFile.exists()) {
				String s = path.substring(0,path.lastIndexOf("/") + 1);
				File saveFileDir = new File(s);
				saveFileDir.mkdirs();
			}
			PubMethods.generateImage(imageStr,path);
			resultMap.put("result","succeess");
			resultMap.put("failMsg","");
			resultMap.put("imageName",imageName);
		} catch (Exception e) {
			resultMap.put("failMsg", "操作失败");
			e.printStackTrace();
			logger.error("上传失败", e);

		} finally {
			logger.info("上传or修改实验报告的图片返回的结果为："+resultMap);
			PubMethods.postMed(response,mapper,resultMap);
		}
	}
}